package myJs.user

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg._
import myJs.myPkg.jquery._
import scalatags.Text.all
import scalatags.Text.all._
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.collection.mutable.ArrayBuffer
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation._


/**
 * Created by yz on 2019/3/6
 */
@JSExportTopLevel("DataView")
object DataView {

  val tableId = "table"
  val headerMap =VarTool.headerMap
  val fieldNames = VarTool.totalFieldNames

  @JSExport("init")
  def init = {
    initTable
    refreshTableView
    refreshTableData()
  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case "barcode" => {
      val detailUrl = g.jsRoutes.controllers.userC.DataController.detailInfoBefore().url.toString
      a(title := "详情", href := s"${detailUrl}?barcode=${row("barcode")}", cursor.pointer, target := "_blank",
        v.toString
      ).render
    }
    case _ => v
  }

  def initTable = {
    val table = tableId
    val columnNames = fieldNames
    val columns = columnNames.map { columnName =>
      val title = headerMap.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt)
    }
    val options = TableOptions.columns(columns.toJSArray)
    $(s"#${tableId}").bootstrapTable(options)
  }

  def refreshTableView = {
    val names = fieldNames
    val nameMap = names.map { x =>
      (x -> headerMap.getOrElse(x, x))
    }
    val html = nameMap.map { case (field, name) =>
      label(marginRight := 15,
        input(`type` := "checkbox", checked, value := field, onclick := s"Utils.setColumns('${field}','${tableId}')", name)
      )
    }.mkString
    $("#checkbox").html(html)
    val hideColumns = names.filterNot { x =>
      (headerMap.keyList ::: List("ExonicFunc.refGene", "aaChangeRefGene")).contains(x)
    }
    hideColumns.foreach { x =>
      $("#table").bootstrapTable("hideColumn", x)
      $(s"input:checkbox[value='${x}']").attr("checked", false)
    }
  }

  def refreshTableData(f: () => js.Any = () => ()) = {
    val url = g.jsRoutes.controllers.DataController.getAllData().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).`type`("get").success { (data, status, e) =>
      $("#table").bootstrapTable("load", data)
      f()
    }
    $.ajax(ajaxSettings)
  }

}
